package model

import (
	"database/sql"

	"github.com/go-xorm/xorm"
)

// PublicRecord represents the t_publicrecord table.
type PublicRecord struct {
	BARBM    string          `xorm:"'barbm' pk notnull"`
	BKRECD   string          `xorm:"'bkrecd'"`
	LIBRQ    string          `xorm:"'librq'"`
	Address  string          `xorm:"'address'"`
	LType    string          `xorm:"'ltype'"`
	Remark   sql.NullString  `xorm:"'remark' null"`
	GOX      string          `xorm:"'gox'"`
	AutherBM sql.NullString  `xorm:"'autherbm' null"`
	JCRQ     sql.NullString  `xorm:"'jcrq' null"`
	JCTM     sql.NullString  `xorm:"'jctm' null"`
	YHRQ     string          `xorm:"'yhrq'"`
	Signal   sql.NullString  `xorm:"'signal' null"`
	XJTMS    sql.NullString  `xorm:"'xjtms' null"`
	LJTMS    sql.NullString  `xorm:"'ljtms' null"`
	LJDT     sql.NullString  `xorm:"'ljdt' null"`
	EPrice   sql.NullFloat64 `xorm:"'eprice' null"`
	Price    string          `xorm:"'price'"`
	ZZSIGNAL sql.NullString  `xorm:"'zzsignal' null"`
	CFJLBM   sql.NullString  `xorm:"'cfjlbm' null"`
	FZC      sql.NullString  `xorm:"'fzc' null"`
	FZ       sql.NullString  `xorm:"'fz' null"`
	QKJQ     sql.NullString  `xorm:"'qkjq' null"`
	CDR      string          `xorm:"'cdr'"`
	YSBH     sql.NullString  `xorm:"'ysbh' null"`
	YSN      sql.NullString  `xorm:"'ysn' null"`
}

// TableName returns the name of the table in the database.
func (p PublicRecord) TableName() string {
	return "t_publicrecord"
}

// CreatePublicRecord creates a new record in the database.

// GetPublicRecord retrieves a record by barbm from the database.
func GetPublicRecord(engine *xorm.Engine, barbm string) (*PublicRecord, error) {
	record := new(PublicRecord)
	has, err := engine.Where("barbm = ?", barbm).Get(record)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, xorm.ErrNotExist
	}
	return record, nil
}

// UpdatePublicRecord updates a record in the database.
func UpdatePublicRecord(engine *xorm.Engine, newRecord *PublicRecord) error {
	session := engine.NewSession()
	defer session.Close()
	if err := session.Begin(); err != nil {
		return err
	}
	_, err := session.ID(newRecord.BARBM).Update(newRecord)
	if err != nil {
		if rErr := session.Rollback(); rErr != nil {
			return rErr
		}
		return err
	}
	if err := session.Commit(); err != nil {
		return err
	}
	return nil
}

// GetPbBookRecord retrieves a record with associated Book by autherbm.
func GetPbBookRecord(engine *xorm.Engine, autherbm string) ([]*PublicRecord, error) {
	var records []*PublicRecord
	err := engine.Where("autherbm = ?", autherbm).Find(&records)
	if err != nil {
		return nil, err
	}

	return records, nil
}

// GetPbBookRecordBy retrieves a record with associated Book by barbm.
func GetPbBookRecordBy(engine *xorm.Engine, barbm string) (*PublicRecord, error) {
	record := new(PublicRecord)
	has, err := engine.Where("barbm = ?", barbm).Get(record)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, xorm.ErrNotExist
	}
	return record, nil
}
